package com.slmxz.tms.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.slmxz.tms.biz.mapper.OrderLifecycleMapper;
import com.slmxz.tms.biz.model.entity.OrderLifecycle;
import com.slmxz.tms.biz.service.OrderLifecycleService;
import com.slmxz.tms.common.component.PrimaryKeyGeneratorService;
import com.slmxz.tms.common.enums.TableEnum;
import com.slmxz.tms.core.service.PrimaryKeySerivce;
import com.slmxz.tms.system.model.vo.UserInfoVO;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单生命周期服务实现类
 *
 * @author sunyao
 *@Date 2024-10-15 21:49
 */
@Service
@RequiredArgsConstructor
public class OrderLifecycleServiceImpl extends ServiceImpl<OrderLifecycleMapper, OrderLifecycle> implements OrderLifecycleService, PrimaryKeySerivce<OrderLifecycle> {

    @Override
    public List<OrderLifecycle> selectOrderLifecycle(String orderNo) {
        //查询订单生命周期
        QueryWrapper<OrderLifecycle> orderLifecycleQuery = new QueryWrapper<>();
        orderLifecycleQuery.lambda().eq(OrderLifecycle::getOrderNo,orderNo)
                .orderByAsc(OrderLifecycle::getId)
                .select(OrderLifecycle::getId,OrderLifecycle::getOperateItem,OrderLifecycle::getContentDesc,OrderLifecycle::getOrderNo,
                        OrderLifecycle::getOperatorName,OrderLifecycle::getOperateTime);
        return this.list(orderLifecycleQuery);
    }

    @Override
    public OrderLifecycle selectOrderDetail(Long id) {
        return this.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Async
    public void orderOperateRecord(List<OrderLifecycle> orderLifecycles, UserInfoVO user) throws Exception {
        LocalDateTime currentTime = LocalDateTime.now();
        for (OrderLifecycle orderLifecycle : orderLifecycles){
            //生成ID
            Long id = this.getId();
            orderLifecycle.setId(id);
            orderLifecycle.setOperateTime(currentTime);
            orderLifecycle.setOpeatorId(user.getId());
            orderLifecycle.setOperatorName(user.getNickname());
        }
        this.baseMapper.batchInsert(orderLifecycles);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Async
    public void orderOperateRecord(OrderLifecycle orderLifecycle, UserInfoVO user) throws Exception {
        //生成ID
        Long id = PrimaryKeyGeneratorService.generateId(TableEnum.TABLE_ORDER_LIFECYCLE);
        orderLifecycle.setId(id);
        orderLifecycle.setOperateTime(LocalDateTime.now());
        orderLifecycle.setOpeatorId(user.getId());
        orderLifecycle.setOperatorName(user.getNickname());
        this.save(orderLifecycle);
    }
}
